本文共 2364 字,大约阅读时间需要 7 分钟。
前端发送请求的时候需要自带一个action参数,用于寻找Servlet中是否存在这个方法。
建立一个Servlet基类,并重写service方法,主要实现判断自己的这个类中是否存在action参数值中对等的方法,如果有调用invoke方法执行这个方法。
其他的Servlet继承这个基类,并写下不同请求所对应的不同方法,因为继承基类,所以当前端发送请求时会自动执行基类中的service方法,因此就相当于在这个Servlet类中是否存在action参数值的方法。基类:
import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.lang.reflect.Method;public class BaseServlet extends HttpServlet { protected void service (HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException { request.setCharacterEncoding("utf-8"); // 接收前端发送的action参数 String action = request.getParameter("action"); // 获取类的字节码 Class clazz = this.getClass(); Method method = null; try { // 获取类中的方法 method = clazz.getMethod(action, HttpServletRequest.class, HttpServletResponse.class); if(method!=null) { // 调用方法 String desPath = (String)method.invoke(this,request,response); if(desPath!=null) { // 指执行完方法后跳转的位置 request.getRequestDispatcher(desPath).forward(request,response); } } } catch (Exception e) { e.printStackTrace(); } }}
测试Servlet类:
import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;@WebServlet("/TestServlet")public class TestServlet extends BaseServlet { // 处理请求1 public String Test1(HttpServletRequest request,HttpServletResponse response) { System.out.println("This is Test1"); return "/TestServlet?action=Test2"; } // 处理请求2 public String Test2(HttpServletRequest request,HttpServletResponse response) { System.out.println("This is Test2"); return "index.jsp"; }}
前端:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>$Title$ click me
此测试是index向Test1发送请求,然Test1处理完后转发到Test2,Test2再转发到index
运行结果:转载地址:http://sdaen.baihongyu.com/